package com.sphd.beautysalon.fragments;

import android.content.DialogInterface;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sphd.beautysalon.adapters.ApplyForAdapter;
import com.sphd.beautysalon.base.LazyLoadFragment;
import com.sphd.beautysalon.base.RestaurantUrl;
import com.sphd.beautysalon.info.ApplyForInfo;
import com.sphd.beautysalon.info.LoginInfo;
import com.sphd.beautysalon.info.RestaurantInfo;
import com.sphd.beautysalon.utils.Constant;
import com.sphd.beautysalon.view.ApplyForView;
import com.sphd.beautysalon.R;
import com.sphd.beautysalon.info.InvestRuleInfo;
import com.sphd.beautysalon.presenter.ApplyForPresenterImpl;
import com.wzh.frame.utils.BigDisMailUtils;
import com.wzh.frame.utils.StringUtils;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Hu on 2017/1/4.
 */

public class ApplyForFragment extends LazyLoadFragment implements ApplyForView, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.my_recy)
    RecyclerView myRecy;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    RestaurantInfo restaurantInfo;
    int type;//分离是哪个状态功能页
    int pos;//当前页面的页面
    ApplyForPresenterImpl applyForPresenter;
    LoginInfo loginInfo;
    ApplyForAdapter applyForAdapter;
    InvestRuleInfo investRuleInfo;
    private AlertDialog dialog;
    @Override
    public int getLayout() {
        return R.layout.swf_and_recy;
    }

    @Override
    public void initViews(View view) {
        ButterKnife.bind(this, view);
        initView();
        initEvent();
    }

    private void initEvent() {
        mySwf.setOnRefreshListener(this);
        myRecy.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                ApplyForInfo applyForInfo = (ApplyForInfo) baseQuickAdapter.getItem(i);
                if (type == 3 && pos == 1 && applyForInfo.getApply_type() == 0 && applyForInfo.getApply_status() == 1) {
                    sendDialog("确定已收到回款" + applyForInfo.getRatify_money() + "元?", applyForInfo);
                } else if (type != 3 && pos == 0) {
                    showSureDialog(applyForInfo);
                }
            }
        });
    }

    private void initView() {
        loginInfo = DataSupport.findLast(LoginInfo.class);
        applyForPresenter = new ApplyForPresenterImpl(this);
        setRefresh(mySwf);
        setRecy(myRecy);
        applyForAdapter = new ApplyForAdapter(R.layout.item_apply, new ArrayList<>(), context);
        myRecy.setAdapter(applyForAdapter);

    }

    @Override
    public void loadData() {
        addData();
    }

    private void addData() {
        if (type == 3) {
            applyForPresenter.addPersonRecord(RestaurantUrl.Httptitle + RestaurantUrl.PERSONRECORD + "cgid=" + restaurantInfo.getId() + "&phone="
                    + loginInfo.getStaff_phone() + "&status=" + pos);
        } else {
            applyForPresenter.addPersonRecord(RestaurantUrl.Httptitle + RestaurantUrl.APAPPLY + "cgid=" + restaurantInfo.getId() + "&type=" + type
                    + "&status=" + pos);
        }
    }

    private void sendDialog(String s1, ApplyForInfo applyInfo) {

        AlertDialog alertDialog = new AlertDialog.Builder(getContext()).setTitle(s1).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        applyForPresenter.sureMoney(RestaurantUrl.Httptitle + RestaurantUrl.AFFRIMREMONEY + "id="
                                + applyInfo.getId() + "&phone=" + loginInfo.getStaff_phone() + "&money=" + applyInfo.getRatify_money());


                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).create();
        alertDialog.setCanceledOnTouchOutside(false);//使除了dialog以外的地方不能被点击
        alertDialog.show();

    }

    @Override
    public void recRes(int res) {
        if (res == 1) {
            toast("操作成功");
            if (dialog!=null&&dialog.isShowing()){
                dialog.dismiss();
            }
        } else {
            toast("操作失败，请重试！");
        }

        onRefresh();
    }

    public void sendDate(RestaurantInfo restaurantInfo, int pos, int type, InvestRuleInfo investRuleInfo) {
        this.restaurantInfo = restaurantInfo;
        this.type = type;
        this.pos = pos;
        this.investRuleInfo = investRuleInfo;
    }

    @Override
    public void sendPersonRecord(List<ApplyForInfo> applyForInfos) {
        applyForAdapter.setType(type, pos);
        applyForAdapter.setNewData(applyForInfos);
    }

    @Override
    public void onRefresh() {
        addData();
    }


    private void showSureDialog(ApplyForInfo applyForInfo) {
        View view = View.inflate(context, R.layout.dialog_wait, null);
        final TextView myMoney = (TextView) view.findViewById(R.id.m_my_money);
        final TextView title = (TextView) view.findViewById(R.id.title);
        final EditText applyMoney = (EditText) view.findViewById(R.id.m_apply_money);
        final EditText reResion = (EditText) view.findViewById(R.id.m_re_resion);
        Button btnApply = (Button) view.findViewById(R.id.btn_apply);
        Button btnRe = (Button) view.findViewById(R.id.btn_re);
        Button btnCancle = (Button) view.findViewById(R.id.btn_cancel);
        if (applyForInfo.getApply_type() == 1) {

            title.setText("申请投入资金");
        } else {
            title.setText("申请撤出资金");

        }
         dialog = new AlertDialog.Builder(getContext()).setView(view)//在这里把写好的这个listview的布局加载dialog中
                .create();
        dialog.setCanceledOnTouchOutside(false);//使除了dialog以外的地方不能被点击
        dialog.show();

        myMoney.setText(BigDisMailUtils.turnTrim(applyForInfo.getApply_money(), Constant.DECIMAL_POINT_TWO));


        btnApply.setOnClickListener(v -> {
            String textMoney = applyMoney.getText().toString();
            if (StringUtils.isEmpty(textMoney)) {
                textMoney = String.valueOf(applyForInfo.getApply_money());
            } else {
                if (!StringUtils.isNoHeard(textMoney)) {
                    toast("请输入合理的金额");
                } else if (Double.parseDouble(textMoney) >
                        applyForInfo.getApply_money()) {
                    toast("金额不能为大于申请金额");
                }
            }
            confirmMoney(textMoney, reResion, 1, applyForInfo);
        });
        btnRe.setOnClickListener(v -> {
            String textMoney = applyMoney.getText().toString();
            if (!StringUtils.isEmpty(textMoney)) {
                toast("请取消输入框中的金额");
            } else {
                confirmMoney(String.valueOf(applyForInfo.getApply_money()), reResion, 2, applyForInfo);
            }
        });
        btnCancle.setOnClickListener(v -> dialog.dismiss());
    }

    private void confirmMoney(String textMoney, EditText reResion, int i, ApplyForInfo applyForInfo) {
        applyForPresenter.sureMoney(RestaurantUrl.Httptitle + RestaurantUrl.RATIFYANDRE +
                "&id=" + applyForInfo.getId() +
                "&cgid=" + restaurantInfo.getId() +
                "&permillage=" + investRuleInfo.getAccount_permillage() +
                "&apply_phone=" + applyForInfo.getApply_phone() +
                "&apply_name=" +StringUtils.utf8Encode(applyForInfo.getApply_name()) +
                "&staffid=" + applyForInfo.getApply_staffid() +
                "&money=" + textMoney +
                "&remark=" + (StringUtils.isEmpty(reResion.getText().toString()) ? StringUtils.utf8Encode("电话联系") :
                StringUtils.utf8Encode(reResion.getText().toString().trim()))
                + "&type=" + type +
                "&status=" + i +
                "&ratify_phone=" + loginInfo.getStaff_phone());
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();
        mySwf.setRefreshing(false);
    }
}
